<!-- 体检套餐页面  zxy-2022-12-28 -->
<script setup lang='ts' name="PhysicalPackage">
import {reactive, ref } from 'vue'
import { ElMessageBox, FormRules} from 'element-plus'
import {ColorTheme, ColorRed} from '@/api/config'
import {HeaderData, Operation as Oper} from '@/components/dTable/dTable'
import { SearchFromItem, SearchButton, SearchFromJustify, OperButton} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'


import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import httpService, { LeftTableDataType, LeftTableDataFormType } from '@/api/physicalExaminationManager/physicalPackage'
import midTable from './midTable.vue'
import rightTable from './rightTable.vue'
import addDialog from './addDialog.vue'
import addGuide from './addGuide.vue'


const addDialogRef = ref() // 新增组件ref
const midTableRef = ref() // 中间表格ref
const rightTableRef = ref() // 右侧表格ref

// 新增套餐
const operButtons = ref<Array<OperButton>>([
  {code:'add', label:'新增', type:'noraml', iconConfig:{icon:'common-add', type:'custom'} }
])

// 套餐操作
const leftRowOperButtons:Array<Oper> = [
  {code:'edit', label:'编辑', iconConfig:{icon:'common-edit', type:'custom', color:ColorTheme, size:20}},
  {code:'setGuide', label:'配置引导单', iconConfig:{icon:'common-maintain', type:'custom', color:ColorTheme, size:20}},
  // {code:'setDefault', label:'设为默认', iconConfig:{icon:'common-selected-no', type:'custom', color:ColorTheme, size:20}},
  // {code:'cancelDefault', label:'取消默认', iconConfig:{icon:'common-selected-yes', type:'custom', color:ColorTheme, size:20}},
  {code:'delete', label:'删除', iconConfig:{icon:'common-delete', type:'custom', color:ColorRed, size:20}}
]

// 左侧套餐表格数据
const leftTableData = ref<Array<LeftTableDataType>>([])

// 左侧表格选中行
const seleteItem = ref<LeftTableDataType>()

// 左侧表格加载状态
const showLeftLoading = ref(false)

// 左侧套餐表格表头
const leftTableHeader = ref<Array<HeaderData>>([
  {prop:'packageCode', label:'套餐编码', columnType:'text', 'min-width':'120' },
  {prop:'packageName', label:'套餐名称', columnType:'text',  'min-width':'140'},
  {prop:'genderName', label:'适用性别', columnType:'text',  'min-width':'90'},
  {prop:'ageRange', label:'年龄范围', columnType:'text',  'min-width':'120'},
  {prop:'pastHistoryName', label:'既往史', columnType:'text',  'min-width':'80'},
  // {prop:'packagePrice', label:'套餐价格（元）', columnType:'text', align:'center', 'min-width':'140'},
  // {prop:'itemGroupPrice', label:'项目组合总价（元）', columnType:'text', align:'center', 'min-width':'160'},
  {prop:'oper', label:'操作', columnType:'slot',  'width':'130', fixed:'right'}
])

// 左侧套餐表格搜索项设置
const leftSearchItems = ref<Array<SearchFromItem>>([
  {label:'套餐名称', placeholder:'请输入套餐名称', prop:'packageName', type:'input', enterSubmit:true, style:{width:'360px'} }
])

// 左侧套餐表格搜索项绑定数据
const leftSearchData = reactive({packageName:'', checkupType :'', province:'', city:''})

// 左侧套餐表格搜索规则
const searchFormRules = reactive<FormRules>({
  packageName: [
    { required: false, message: '长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ]
})

// 搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type:'search'},
  {type:'clear'}
])

// 搜索项flex左对齐
const searchFromJustify = ref<SearchFromJustify>('flexStart')

const rowDataBase:LeftTableDataFormType = {
  id: undefined, // 此行id
  packageCode: '', // 套餐code
  packageName: '', // 套餐名称
  tips:'',
  isDefault: false,
  packageGuideList:[]

}
// 选中行
const curRowData = ref<LeftTableDataFormType>({...rowDataBase})

//分页配置
const tablePageConfig = ref<PageConfig>({
  currentPage:defaultPage,
  pageSize:defaultPageSize,
  pageSizes:defaultPageSizes,
  total:0,
  disabled:false,
  layout:defaultLayout
})

// 表格按钮操作
const onTableOperation = (name:string) => {
  if (name === 'add') {
    addDialogRef.value.openDialog('add')
  }
}

// 行点击数据
const onRowClick = (row:LeftTableDataType) => {
  if (row === null) return
  curRowData.value = {...row}
  midTableRef.value?.setFormSearchClear()
  midTableRef.value?.getMidTableData(row)
  rightTableRef.value?.setFormSearchClear()
  rightTableRef.value?.getRightTableData(true, row.id)
}


// 初始化搜索条件
const initSearchData = () => {
  leftSearchData.packageName = ''
  leftSearchData.checkupType = ''
}

// 表格数据赋值
const setTableData = (data:Array<LeftTableDataType>) => {
  if (!data.length) {
    midTableRef.value.setMidTableDataNone()
    rightTableRef.value.setRightTableDataNone()
  }
  data.forEach((item) => {
    if (!item.packageGuideList) {
      item.packageGuideList = []
    }

    item.oper = leftRowOperButtons
    // .filter(oper => {
    //   if (item.isDefault) {
    //     return oper.code !== 'setDefault'
    //   } else {
    //     return oper.code !== 'cancelDefault'
    //   }
    // })

  })
  leftTableData.value = data
  // console.log('curRowData.value.id', curRowData.value.id)
  const tempCurrRowData = data.find(item => item.id === curRowData.value.id)

  seleteItem.value = tempCurrRowData ?? data[0]

  // seleteItem.value = data.find(item => item.id === curRowData.value.id)
}

// 获取左侧表格搜索数据
const getLeftTableData = (resetPage?:boolean) => {
  if (resetPage) {
    tablePageConfig.value.currentPage = 1
  }
  httpService.getLeftTableData({
    packageName: leftSearchData.packageName ? leftSearchData.packageName : undefined,
    page: tablePageConfig.value.currentPage,
    limit: tablePageConfig.value.pageSize
  }).then((res) => {
    showLeftLoading.value = false
    const {data} = res.data

    tablePageConfig.value.total = data.total === null ? 0 : data.total
    setTableData(data.records)

  }).catch(() => {
    showLeftLoading.value = false
  })
}

// const setOrCancelDefault = (id, text) => {
//   ElMessageBox.confirm(
//     text,
//     '提示',
//     {
//       confirmButtonText: '确认',
//       cancelButtonText: '取消',
//       type: 'warning'
//     }
//   ).then(() => {
//     httpService.setDefaultPackage(id).then(() => {
//       getLeftTableData()
//     })
//   })
// }
const showGuideDialog = ref<boolean>(false)
// 左侧表格行操作
const leftCellOperation = (name:string, row) => {
  if (name === 'edit') {
    addDialogRef.value?.openDialog('edit', row)
  } else if (name === 'setGuide') {
    curRowData.value = {...row}
    showGuideDialog.value = true
  // } else if (name === 'setDefault') {
  //   setOrCancelDefault(row.id, '是否确认将此套餐设为默认套餐？')
  // } else if (name === 'cancelDefault') {
  //   setOrCancelDefault(row.id, '是否确认取消设置此默认套餐')
  } else if (name === 'delete') {
    ElMessageBox.confirm(
      '确认删除体检套餐：' + row.packageName,
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      httpService.deleteRow(row.id).then(() => {
        getLeftTableData()
      })
    })
  }
}

const closeGuideDialog = () => {
  showGuideDialog.value = false
  getLeftTableData()
  // curRowData = {...rowDataBase}
}

// 表格每页多少行变化
const onSizeChange = () => {
  getLeftTableData(true)
}

// 表格第几行变化
const onPageNoChange = () => {
  getLeftTableData(false)
}

//搜索事件
const onSubmit = () => {
  getLeftTableData(true)
}

//清空搜索表单事件
const onReset = () => {
  initSearchData()
  getLeftTableData(true)
}

// 刷新表格
const refreshTable = () => {
  getLeftTableData()
}

// 添加项目组合
const addInspect = (itemGroupId) => {
  if (!curRowData.value?.id) return
  httpService.addInspect({packageId:curRowData.value.id, itemGroupId:itemGroupId}).then(() => {
    getLeftTableData()
  }).catch(() => {
    getLeftTableData()
  })
}

// 移除项目组合
const removeInspect = (itemGroupId) => {
  if (!curRowData.value?.id) return
  httpService.removeInspect({packageId:curRowData.value.id, itemGroupId:itemGroupId}).then(() => {
    getLeftTableData()
  }).catch(() => {
    getLeftTableData()
  })
}


// 初始化请求
getLeftTableData(true)

</script>

<template>
  <page-container>
    <div class="inspection-package">
      <div class="left-table-content">
        <d-table-promote
          :label-width="70"
          :show-index="false"
          :search-form-items="leftSearchItems"
          :search-form-data="leftSearchData"
          :search-rules="searchFormRules"
          :search-buttons="searchButtons"
          :table-data="leftTableData"
          :table-header-data="leftTableHeader"
          :page-config="tablePageConfig"
          :search-from-justify="searchFromJustify"
          :show-loading="showLeftLoading"
          :default-seleted="seleteItem"
          :oper-buttons="operButtons"
          @form-submit="onSubmit"
          @form-clear="onReset"
          @operation="onTableOperation"
          @size-change="onSizeChange"
          @current-change="onPageNoChange"
          @row-click="onRowClick"
        >
          <template #oper="scope">
            <operation class="table-cell-oper" :row="scope.row" :col="scope.item" @opertion-click="leftCellOperation" />
          </template>
        </d-table-promote>
      </div>
      <div class="space space1" />
      <div class="mid-table-content">
        <mid-table ref="midTableRef" @remove-inspect="removeInspect" />
      </div>
      <div class="space space2" />
      <div class="right-table-content">
        <right-table ref="rightTableRef" @add-inspect="addInspect" />
      </div>
    </div>
  </page-container>
  <add-dialog ref="addDialogRef" @refresh-table="refreshTable" />
  <add-guide v-if="showGuideDialog" :show-dialog="showGuideDialog" :data="curRowData" @close="closeGuideDialog" />
</template>

<style scoped lang="less">
.space {
  margin: 0 13px;
  background-color: var(--d-color-grey-1);
  height: 100%;
}
.space1{
  width: 6px;
}
.space2 {
  width: 2px;
}
.inspection-package {
  display: flex;
  width: 100%;
  height: 100%;
}
.left-table-content {
  flex: 2.1;
}
.right-table-content {
  flex: 1.1;
  min-width: 270px;
}
.mid-table-content {
  flex: 1;
  min-width: 270px;
}
.table-cell-oper {
  display: flex;
  justify-content: center;
}
</style>
